import Vue from 'vue'
import VueRouter from 'vue-router'

import Lease from '@/views/lease'
import Collect from '@/views/collect'
import Login from '@/views/login'
import Register from '@/views/register'
import Layout from '@/views/layout'
import Homepage from '@/views/homepage'
import Find from '@/views/find'
import Information from '@/views/information'
import My from '@/views/my'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  { path: '/collect', component: Collect },
  { path: '/lease', component: Lease },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: Layout,
    redirect: '/homepage',
    children: [
      {
        path: '/homepage',
        component: Homepage
      },
      {
        path: '/find',
        component: Find
      },
      {
        path: '/information',
        component: Information
      },
      {
        path: '/my',
        component: My
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫：
// 1. 所有的路由一旦被匹配到，在真正渲染解析之前，都会先经过全局前置守卫
// 2. 只有全局前置守卫放行，才能看到真正的页面

// 任何路由，被解析访问前，都会先执行这个回调
// 1. from 你从哪里来， 从哪来的路由信息对象
// 2. to   你往哪里去， 到哪去的路由信息对象
// 3. next() 是否放行，如果next()调用，就是放行 => 放你去想去的页面
//    next(路径) 拦截到某个路径页面
// whiteList: 白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // console.log(to, from)
  // next()
  const token = getToken()
  // 如果有 token 直接放行
  if (token) {
    next()
  } else {
    // 如果没有 token, 就检测是否去的是白名单的页面,如果是,直接放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 否则就让用户去登录页面
      next('/login')
    }
  }
})

export default router
